<?php
/*
Plugin Name: BPDEV-FLICKR
Plugin URI: http://bp-dev.org/projects/#aggregator
Description: Add a page to show own flickr photos for each user
Author: Nicola Greco
Version: 0.3
Author URI: http://nicolagreco.com

Copyright (c) 2009-2011, Nicola Greco (mail: notsecurity@gmail.com | website: http://nicolagreco.com).

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
define( 'BPDEV_FLICKR_NAME', 'BPDEV-FLICKR' );
define( 'BPDEV_FLICKR_VERSION', '0.3' );

require_once( 'bp-core.php' );
require_once( 'bpdev-core.php' );

if ( !get_option( 'bpdev-flickr-status' ) ) add_option( 'bpdev-flickr-status', 'off' );
if ( get_option('bpdev-flickr-status') == "on" ) {

	if ( function_exists('simplepie_init') ) simplepie_init();
	add_action( 'wp', 'bpdev_flickr_setup_globals', 1 ); //add globals on wp
	add_action( '_admin_menu', 'bpdev_flickr_setup_globals', 1 ); //add globals on _admin_menu
	add_action( 'wp', 'bpdev_flickr_setup_nav', 2 );
	add_action( 'bp_custom_profile_boxes', 'flickr_show_profile' );
	add_action( 'bpdev_theme_extra_setup_globals' , 'bpdev_flickr_css' );

}

add_action( 'bpdev_admin_plugins_screen', 'bpdev_flickr_admin_menu_screen', 3 );
add_action( 'bpdev_admin_plugins_save', 'bpdev_flickr_admin_menu_save', 3 );

function bpdev_flickr_setup_globals() {

	global $bp;
	$bp->bpdev->flickr->slug ='flickr';
	$bp->bpdev->flickr->image_base = site_url() . '/wp-content/mu-plugins/bpdev-flickr/images'; //Images
	$bp->bpdev->flickr->css = site_url() . '/' . bpdev_component_dir( $bp->bpdev->flickr->slug ) . 'css/';
	$bp->bpdev->flickr->js = site_url() . '/' . bpdev_component_dir( $bp->bpdev->flickr->slug ) . 'js/';

}

function bpdev_flickr_admin_menu_save() {

	do_action( 'bpdev_admin_save_component', 'bpdev-flickr-status' );

}
function bpdev_flickr_admin_menu_screen() {

	?>

	<h3><?php echo BPDEV_FLICKR_NAME; ?></h3>

	<table class="form-table">

		<tr valign="top">

			<th scope="row">Plugin Version</th>
			<td>
				<?php echo BPDEV_FLICKR_VERSION; ?>
			</td>

		</tr>

		<tr>

			<th scope="row">Plugin Status</th>
			<td>
				<select id="bpdev-flickr-status" name="bpdev-flickr-status">
					<option value="off"  <?php if ( !get_option('bpdev-flickr-status') || get_option('bpdev-flickr-status') == "off") echo 'selected=""'; ?>>Off</option>
					<option value="on" <?php if( get_option('bpdev-flickr-status') == "on") echo 'selected=""'; ?>>On</option>
				</select>
			</td>

		</tr>

	</table>

	<?php

}

function bpdev_flickr_setup_nav() {

	global $bp;
	bp_core_add_nav_item( __('Flickr', 'buddypress'), $bp->bpdev->flickr->slug );
	bp_core_add_nav_default( $bp->bpdev->flickr->slug, 'flickr_show_settings', 'show' ); //Set aggregator_blog_settings as default page
	$flickr_link = $bp->loggedin_user->domain. $bp->bpdev->flickr->slug . '/'; //link for pages
	bp_core_add_subnav_item( $bp->bpdev->flickr->slug, 'show', __('Show', 'buddypress'), $flickr_link, 'flickr_show_settings' );
	bp_core_add_subnav_item( 'settings', 'flickr', __('Flickr Settings', 'buddypress'), $bp->loggedin_user->domain. 'settings/', 'flickr_option_settings', false, bp_is_home() );
	if ( $bp->current_component == $bp->bpdev->flickr->slug ) {
		if ( bp_is_home() ) {
			$bp->bp_options_title = __('Flickr', 'buddypress'); //Area
		} else {
			$bp->bp_options_avatar = bp_core_get_avatar( $bp->displayed_user->id, 1 );
			$bp->bp_options_title = $bp->displayed_user->fullname; 
		}
	}

}


function flickr_show_settings() {

	global $current_user, $bp_settings_updated, $pass_error;
	add_action( 'bp_template_content', 'flickr_show_content' );
	add_action( 'bp_template_content_header', 'flickr_show_title' );
	add_action('wp_head', 'flickr_head_load_js');
	bp_catch_uri('plugin-template');

}


function flickr_head_load_js() { 

	global $bp;
	?>
	
<!--BPDEV-FLICKR PLUGIN LOAD STYLE&CSS START-->
	<script type="text/javascript" src="<?php echo $bp->bpdev->flickr->js; ?>prototype.js"></script>
	<script type="text/javascript" src="<?php echo $bp->bpdev->flickr->js; ?>scriptaculous.js?load=effects,builder"></script>
	<script type="text/javascript" src="<?php echo $bp->bpdev->flickr->js; ?>lightbox.js"></script>
	<link rel="stylesheet" href="<?php echo $bp->bpdev->flickr->css; ?>lightbox.css" type="text/css" media="screen" />
<!--BPDEV-FLICKR PLUGIN LOAD STYLE&CSS STOP -->

	<?php

}


function bpdev_flickr_css() {

	bpdev_theme_register_style(
		'bpdev-flickr', 
		'BPDEV Flickr', 
		array( 'BPDEV_Theme_CSS' , 'bpdev_flickr' ),
		'on',
		'off'
	);

}


function flickr_show_title() {

	bp_word_or_name( __( "My Flickr Photos", 'buddypress' ), __( "%s's Flickr Photos", 'buddypress' ) );

}


function flickr_show_profile() {

	add_action('wp_head', 'flickr_head_load_js');
	$imageclass = new BPDEV_Flickr();
	?>
			<div class="info-group">
				<h4>Last Photos (5) <a href="<?php bpdev_flickr_see_all_link() ?>"><?php _e( "See All &raquo;", "buddypress" ) ?></a></h4>
					<ul class="horiz-gallery">
					     <?php $imageclass->profile_link(); ?>
					     <div class="clear"/>
					</ul>
			</div>
	<?php 
}


function flickr_show_content() {

	global $bp, $current_user, $bp_settings_updated, $pass_error; 
	$imageclass = new BPDEV_Flickr(); ?>
	<div class="left-menu">
		<?php bp_the_avatar() ?>
		
		<div class="button-block">
			<?php if ( function_exists('bp_add_friend_button') ) : ?>
				<?php bp_add_friend_button() ?>
			<?php endif; ?>
			
			<?php if ( function_exists('bp_send_message_button') ) : ?>
				<?php bp_send_message_button() ?>
			<?php endif; ?>
		</div>

		<?php bp_custom_profile_sidebar_boxes() ?>
	</div>

	<div class="main-column">
		<div class="inner-tube">
			<div id="profile-name"><h1 class="fn"><a href="<?php bp_user_link() ?>flickr"><?php bp_word_or_name( __( "My Flickr Photos", 'buddypress' ), __( "%s's Flickr Photos", 'buddypress' ) ); ?></a></h1></div>		
			<div class="info-group">
				<h4>Flickr Profile</h4>
<?php if ( function_exists('simplepie_init') and get_option('bpdev-simplepie-status') != "off" ) { ?>
				<table class="profile-fields"><tbody><tr>
					<td class="label">Username</td>
					<td class="data"><p><a href="http://flickr.com/photos/<?php echo $imageclass->author ?>"><?php echo $imageclass->author ?></a></p></td>
				</tr></tbody></table>
			</div>
			<div class="info-group">
				<h4>Last Photos</h4>
					<ul class="horiz-gallery">
					     <?php $imageclass->image_link(); ?>
					</ul>
			</div>
<?php } else { ?>
<strong>This plugin will not work if you don't install <a href="http://buddypressdev.org/plugins/bpdev-simplepie">BPDEV-SIMPLEPIE LOADER plugin!</a></strong>
<?php } ?>
			<div class="button-block">
				<?php bpdev_flickr_credits(); ?>
			</div>
		</div>
	</div>
	<?php 
	do_action( 'flickr_show_content_right' );

} 
function flickr_option_settings() {

	global $current_user, $bp_settings_updated, $pass_error;
	$bp_settings_updated = false;
	$pass_error = false;

	if (isset($_POST['save_bpdev_flickr_submit']) && check_admin_referer('bp_settings_flickr')) {

		$option_tags = $_POST['tags'];
		$option_set = $_POST['set'];
		$option_num2disp = $_POST['num2disp'];
		$option_type = $_POST['display_type'];
		$option_flickrid = $_POST['flickrid'];

		update_usermeta( (int)$current_user->id,'bpdev_flickr_data_flickrid', $option_flickrid);
		update_usermeta( (int)$current_user->id,'bpdev_flickr_data_tags', $option_tags);
		update_usermeta( (int)$current_user->id,'bpdev_flickr_data_set', $option_set);
		update_usermeta( (int)$current_user->id,'bpdev_flickr_data_num2disp', $option_num2disp);
		update_usermeta( (int)$current_user->id,'bpdev_flickr_data_display_type', $option_type);

	}

	add_action( 'bp_template_title', 'flickr_option_title' );
	add_action( 'bp_template_content', 'flickr_option_content' );
//	add_action( 'bp_template_content_header', 'flickr_option_tabs' );
	bp_catch_uri('plugin-template');

}


function flickr_option_title() {

	_e( 'Flickr Photo Settings', 'buddypress' );

}


function flickr_option_content() {
	global $bp, $current_user, $bp_settings_updated, $pass_error;
	if ( $bp_settings_updated && !$pass_error ) { ?>
		<div id="message" class="updated fade">
			<p><?php _e( 'Changes Saved.', 'buddypress' ) ?></p>
		</div>
	<?php } ?>

	<?php if ( $pass_error && !$bp_settings_updated ) { ?>
		<div id="message" class="error fade">
			<p><?php _e( 'Your passwords did not match', 'buddypress' ) ?></p>
		</div>
	<?php } ?>		
	<form action="<?php echo $bp->loggedin_user->domain. 'settings/flickr' ?>" method="post" id="settings-form">
		<table class="form-table">
		 <tr valign="top">
		  <th scope="row">Flickr ID</th>
	      <td><input name="flickrid" type="text" id="flickrid" value="<?php echo $current_user->bpdev_flickr_data_flickrid; ?>" size="20" />
        		Use the <a href="http://idgettr.com">idGettr</a> to find your user or group id.</p></td>
         </tr>
         <tr valign="top">
          <th scope="row">Display</th>
          <td>
        	<select name="display_type" id="display_type">
        	  <option <?php if($current_user->bpdev_flickr_data_display_type == 'user') { echo 'selected'; } ?> value="user">user</option>
        	  <option <?php if($current_user->bpdev_flickr_data_display_type == 'set') { echo 'selected'; } ?> value="set">set</option>
        	  <option <?php if($current_user->bpdev_flickr_data_display_type == 'favorite') { echo 'selected'; } ?> value="favorite">favorite</option>
		      <option <?php if($current_user->bpdev_flickr_data_display_type == 'group') { echo 'selected'; } ?> value="group">group</option>
		      <option <?php if($current_user->bpdev_flickr_data_display_type == 'community') { echo 'selected'; } ?> value="community">community</option>
		    </select>
		 	items using 
        	<select name="num2disp" id="num2disp">
		      <option <?php if($current_user->bpdev_flickr_data_num2disp == '5') { echo 'selected'; } ?> value="5">5</option>
		      <option <?php if($current_user->bpdev_flickr_data_num2disp == '10') { echo 'selected'; } ?> value="10">10</option>
		      <option <?php if($current_user->bpdev_flickr_data_num2disp == '15') { echo 'selected'; } ?> value="15">15</option>
		      <option <?php if($current_user->bpdev_flickr_data_num2disp == '20') { echo 'selected'; } ?> value="20">20</option>
		</select>
           </td> 
         </tr>
         <tr valign="top">
		  <th scope="row">Set</th>
          <td><input name="set" type="text" id="set" value="<?php echo $current_user->bpdev_flickr_data_set; ?>" size="40" /> Use number from the set url</p>
         </tr>
         <tr valign="top">
		  <th scope="row">Tags</th>
          <td><input name="tags" type="text" id="tags" value="<?php echo $current_user->bpdev_flickr_data_tags; ?>" size="40" /> Comma separated, no spaces</p>
         </tr>
         </table>      
        <div class="submit">
           <input type="submit" name="save_bpdev_flickr_submit" value="<?php _e('Save Settings', 'buddypress') ?>" />
	<?php wp_nonce_field('bp_settings_flickr') ?>
        </div>
        </form>
	<?php
}


class ImgPie {

	function cleanup( $s = null ) {
		if ( !$s ) return false;
		else {
			return str_replace('"', '', $s);
		}
	}

	function photo( $url, $size ) {
		$url = explode( '/', $url );
		$photo = array_pop( $url );
		switch($size) {
			case 'square':
				$r = preg_replace('/(_(s|t|m|b))?\./i', '_s.', $photo);
				break;
			default: // Medium
				$r = preg_replace('/(_(s|t|m|b))?\./i', '.', $photo);
				break;
		}
		$url[] = $r;
		return implode('/', $url);
	}

	function find_photo($data) {
		preg_match_all('/<img src="([^"]*)"([^>]*)>/i', $data, $m);
		return $m[1][0];
	}

}

class BPDEV_Flickr {

	var $num2disp, $type, $tags, $imagesize, $before_image, $after_image, $id_number, $set_id, $full_url, $thumb_url, $title, $all, $author, $user_id;

	function BPDEV_Flickr( $user_id = false ) {

		global $bp;

		if ( $userid ) {

			$this->user_id = $userid;

		} else {

			$this->user_id = $bp->displayed_user->id;

		}

		$this->num2disp = get_usermeta( $this->user_id , 'bpdev_flickr_data_num2disp');
		$this->type = get_usermeta( $this->user_id , 'bpdev_flickr_data_display_type' );
		$this->tags = trim( get_usermeta( $this->user_id , 'bpdev_flickr_data_tags') );
		$this->id_number = stripslashes( get_usermeta( $this->user_id , 'bpdev_flickr_data_flickrid' ) );
		$this->set_id = stripslashes( get_usermeta( $this->user_id , 'bpdev_flickr_data_set' ) );
		$this->parse_flickr();

	}

	function parse_flickr() {

		error_reporting(E_ERROR);

		if ($this->type == "user") { $rss_url = 'http://api.flickr.com/services/feeds/photos_public.gne?id=' . $this->id_number . '&tags=' . $this->tags . '&format=atom'; }
		elseif ($this->type == "favorite") { $rss_url = 'http://api.flickr.com/services/feeds/photos_faves.gne?id=' . $this->id_number . '&format=atom'; }
		elseif ($this->type == "set") { $rss_url = 'http://api.flickr.com/services/feeds/photoset.gne?set=' . $this->set_id . '&nsid=' . $this->id_number . '&format=atom'; }
		elseif ($this->type == "group") { $rss_url = 'http://api.flickr.com/services/feeds/groups_pool.gne?id=' . $this->id_number . '&format=atom'; }
		elseif ($this->type == "community" || $this->type == "public") { $rss_url = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=' . $this->tags . '&format=atom'; }
		else { $this->error = "This user hasn't set up this page."; }

		if ( function_exists( 'simplepie_init' ) and get_option( 'bpdev-simplepie-status' ) != "off" ) {
			simplepie_init();
			$rss = new SimplePie($rss_url);
			$rss->handle_content_type();

			if ($rss) {

				$items = array_slice($rss->get_items(), 0, $this->num2disp);
				$count = 0;

				foreach ( $items as $item ) {

					if ( preg_match( '<img src="([^"]*)" [^/]*/>' , $item->get_description() ,$imgUrlMatches ) ) {

						$author = $item->get_author();
						$this->author = $author->get_name();
						$this->thumb = 'square';
						$this->full = 'medium';
						$this->url = ImgPie::find_photo($item->get_description());
						$this->title = ImgPie::cleanup($item->get_title());
						$this->full_url = ImgPie::photo($this->url, $this->full);
						$this->thumb_url = ImgPie::photo($this->url, $this->thumb);
						$count = $count + 1;
						$this->all[$count] = "<li>\n<a href=\"{$this->full_url}\" title=\"{$this->title}\" rel=\"lightbox\"><img src=\"{$this->thumb_url}\" alt=\"{$this->title}\" class=\"avatar photo\" /></a>\n</li>";

					}

				}

			}

			if ( $this->error ) 
				$this->author = "Not Definied Yet";

		}

	}

	function image_link() {

		if ($this->error) { 

			echo $this->error; 

		} else {

			if ( $this->all ) {

				foreach ( $this->all as $one ) {

					echo $one;

				}

			} else {

				echo $this->error;

			}

		}

	}

	function profile_link() {

		if ($this->error) {

			echo $this->error; 

		} else {

			if ( $this->all ) {

				$items = array_slice($this->all, 0, 5);

				foreach ( $items as $one ) {

					echo $one;

				}

			} else {

				echo $this->error;

			}

		}

	}

}


function bpdev_flickr_see_all_link() {

	global $bp;
	
	if ( $bp->current_item == '')
		$uri = $bp->current_action;
	else
		$uri = $bp->current_item;

	echo apply_filters( 'bpdev_flickr_see_all_link', $bp->displayed_user->domain . $bp->bpdev->flickr->slug );

}


function bpdev_flickr_credits() {

	global $bp;

	if( bp_is_home() ) {

	?>

			<div class="generic-button">
				<a class="edit" title="Edit Profile" href="<?php bp_user_link() ?>settings/flickr">Edit Flickr Settings</a>
			</div>
			<div class="clear"></div>
	<?php } ?>

			<!-- <div class="generic-button"><a href="http://buddypressdev.org/plugins/bpdev-flickr" title="Show Flickr in BuddyPress">Powered by BPDEV-FLICKR</a></div> -->
	
	<?php

	do_action('bpdev_flickr_credits');

}
?>